package com.cy.jt.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.catalina.filters.ExpiresFilter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

public class JsonAuthenticationSuccessHandler implements AuthenticationSuccessHandler{



 @Override
 public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Authentication authentication) throws IOException, ServletException{
  User principal=(User)authentication.getPrincipal();
  System.out.println(principal.getUsername()+"/"+principal.getPassword()+"/"+principal.getAuthorities());
  Object credentials=authentication.getCredentials();
  System.out.println("principal="+principal);
  System.out.println("credentials="+credentials);
  httpServletResponse.setCharacterEncoding("utf-8");
 httpServletResponse.setContentType("application/json;charset=utf-8");
  PrintWriter out=httpServletResponse.getWriter();
  HashMap<String,Object> map=new HashMap<>();
  map.put("state","200");
  map.put("msg","Login ok");
  map.put("username",principal.getUsername());
  String jsonstr=new ObjectMapper().writeValueAsString(map);
  out.println(jsonstr);
//  out.println("{\"state\":200,\"msg\":\"ok\"}");
  out.flush();
 }
}
